# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

isdo = 0
zan_count = 0
zhuanfa_count = 0
liuyan_count = 0
zan_max = 500
zhuanfa_max = 500
liuyan_max = 500
isscroll = 0
willdo = 0
nownum = 0
cn_liuyan = "精彩拍摄"
en_liuyan = "Wonderful shooting"
login_no = '13816146456'
login_pw = "hjy11911xx"
from tkinter import *
from wincener import center


def contain_zh(s):
    for c in s:
        if not ('\u4e00' <= c <= '\u9fa5'):
            return False
    return True


driver = None


# driver = webdriver.Firefox()
def login():
    global driver, login_no, login_pw
    driver = webdriver.Chrome(executable_path='chromedriver.exe')
    driver.implicitly_wait(10)  # 隐性等待
    driver.get('https://500px.me')
    time.sleep(2)
    # driver.maximize_window()
    driver.find_element_by_css_selector("a.login").click()
    # driver.maximize_window()  #将浏览器最大化显示
    time.sleep(3)
    driver.find_element_by_id("userName").send_keys(login_no)
    driver.find_element_by_id("password").send_keys(login_pw)
    driver.find_element_by_id("subButton").click()
    time.sleep(1)
    driver.find_element_by_css_selector("li._subscribeTab").click()
    time.sleep(5)
    # driver.find_element_by_css_selector("a.v2_new_fav").click()


def doit():
    global driver, isdo, willdo, isscroll, zan_count, zhuanfa_count, liuyan_count, zan_max, liuyan_max, cn_liuyan, en_liuyan
    now_handle = driver.current_window_handle  # 获取当前窗口句柄
    main_icons = driver.find_elements_by_class_name("new_icons_maincmp")
    if isscroll > 0:
        main_icons = main_icons[isdo:]
    print("len(main_icons):", len(main_icons))
    isscroll = isscroll + 1
    for icons in main_icons:
        isdo = isdo + 1
        if isdo % 20 == 0:
            time.sleep(2)
        try:
            time.sleep(0.2)
            # driver.execute_script("arguments[0].scrollIntoView();", icons);
            time.sleep(0.2)
            button = icons.find_element_by_class_name("v2_new_fav")
            fav_class = button.get_attribute("class")
            if "hearted" not in fav_class:
                if int(zan_max) > zan_count:
                    button.click()  # 点赞
                    print("点赞")
                    zan_count = zan_count + 1
                else:
                    print("点赞已达最大额度")

            buttons = icons.find_elements_by_class_name("v2_new_zf")
            # print(buttons)
            for button in buttons:
                fav_class = button.get_attribute("class")
                if "hearted" not in fav_class:
                    if int(zhuanfa_max) > zhuanfa_count:
                        # print("点击前")
                        # # time.sleep(3)
                        # print("点击")

                        button.click()  # 转发
                        zfid = button.get_attribute("data-target")

                        print('zfid', zfid)

                        # ActionChains(driver).move_to_element(zfbut)
                        # driver.execute_script("$(arguments[0]).click()",button)
                        # button.click()
                        print("转发点击后")
                        # time.sleep(3)
                        # print(zfid)
                        # time.sleep(13)
                        dozf(driver, zfid, button)
                    else:
                        print("转发已达最大额度")

            if int(liuyan_max) > liuyan_count:
                liuyan_button = icons.find_element_by_class_name("commentTubiao")
                liuyan_button.click()  # 打开留言
                print("打开留言1")
                time.sleep(3)
                # 判断是否有俩窗口driver.window_handles
                ifgb = 0
                for handle in driver.window_handles:
                    if handle != now_handle:
                        driver.switch_to_window(handle)
                        time.sleep(1)
                        ifgb = 1
                        driver.close()  # 关闭当前窗口

                if ifgb == 1:
                    driver.switch_to_window(now_handle)
                    continue
                actors = driver.find_elements_by_class_name("actor")
                liuyan_flag = 0
                for actor in actors:
                    # print(actor)
                    # print(actor.text)
                    if actor.text == 'hjy191':
                        liuyan_flag = 1
                print("liuyan_flag:" + str(liuyan_flag))
                if liuyan_flag == 1:
                    close_but = driver.find_element_by_class_name("close")
                    close_but.click()  # 关闭本留言
                    continue
                liuyan_text = driver.find_element_by_class_name("new_comment")
                # //*[@id="user_show"]/div[12]/div/div/div[2]/div/div[3]/div[2]/div/div[2]/div/div/div[2]/a
                photographer_info = driver.find_element_by_class_name("photographer_info")
                actor_name = photographer_info.find_element_by_class_name("actor")
                # print("actor_name:"+actor_name.text)
                if contain_zh(actor_name.text):
                    liuyan_text.send_keys(cn_liuyan)
                else:
                    liuyan_text.send_keys(en_liuyan)
                print("打开留言2")
                comment_icon = driver.find_element_by_class_name("comment_icon")
                comment_icon.click()
                print("打开留言3")
                close_but = driver.find_element_by_class_name("close")
                close_but.click()  # 关闭本留言
                liuyan_count = liuyan_count + 1
            else:
                print("留言已达最大额度")
        except Exception as e:
            print('出现以下异常：')
            print ('str(Exception):\t', str(Exception))
            print ('str(e):\t\t', str(e))
            print ('repr(e):\t', repr(e))
            continue
        finally:
            print('异常后继续下一个')


            # jiahao_class = driver.find_elements_by_class_name("jiaohao")
            # print(len(jiahao_class))
            # for jiahao in jiahao_class:
            #     print(jiahao)
            #     jiahao.click()
            #     print("加号点击了")
            #     jiahao_class = driver.find_elements_by_class_name("jiaohao")
            # comfirmZf = driver.find_element_by_css_selector("comfirmZf")
            # # comfirmZf.click()
            # print("确认转发")


errcount = 0


def dozf(driver, zfid, button):
    # button.click()
    zfbut11 = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
    # locator = (By.LINK_TEXT, 'lion')
    # WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
    ActionChains(driver).move_to_element(zfbut11).perform()
    button.click()
    if is_element_visible(driver, zfbut11) or 1 == 1:
        # ActionChains(driver).move_to_element(zfbut).perform()
        global errcount, zhuanfa_count
        # print("挪动前,3秒后点击")
        # time.sleep(3)
        # button.click()
        # ActionChains(driver).moveToElement(button).build().perform();
        # parentitem = driver.find_elements_by_xpath('//div[@id = "'+zfid+'"]//div[@class = "inside"]')
        parentitem = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//div[@class = "inside"]')
        print('parentitem', parentitem)
        # for pitem in parentitem:
        print('进入可点循环列表')
        caozk = parentitem
        itemList = caozk.find_elements_by_xpath('//div[@class = "jiaohao"][not(contains(@class, "hasDone"))]')

        # itemList = driver.find_elements_by_xpath('//div[@id = "'+zfid+'"]//div[@class = "jiaohao"][not(contains(@class, "hasDone"))]')
        # webuiPopover60 > div.webui-popover-inner > div > div > div > div > div.inside > div:nth-child(1) > div.jiaohao
        print(len(itemList))
        if len(itemList) < 4:
            zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            # ActionChains(driver).move_to_element(zfbut).perform()
            zfbut.click()

            zhuanfa_count = zhuanfa_count + 1
            return True
        else:
            print(len(itemList))
            i = 1
            jiahao = itemList[len(itemList) - 1]
            # ActionChains(driver).move_to_element(jiahao).perform()

            # driver.execute_script("arguments[0].scrollIntoView();", jiahao)  # 拖动到可见的元素去
            # ActionChains(driver).move_to_element(jiahao).click()
            # print("点击了前,10秒后点击")
            # time.sleep(10)
            # the_element = EC.visibility_of_element_located(jiahao)
            # assert the_element(driver)
            print("1秒后准备加号点击了")
            # button.click()
            time.sleep(0.1)
            # if is_element_visible(driver, jiahao):
            jiahao.click()
            print("1秒后准备加号点击了")
            time.sleep(1)
            zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            print('zfbut')
            # ActionChains(driver).move_to_element(zfbut).perform()
            zfbut.click()
            zhuanfa_count = zhuanfa_count + 1
            return True
            # else:
            #     print("jiahao不可见等5秒")
            #     time.sleep(5)
            #     button.click()
            #     print("jiahao不可见点击后等三秒")
            #     time.sleep(3)
            #     zfbut1 = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     ActionChains(driver).move_to_element(zfbut1).perform()
            #     continue
            #     # ActionChains(driver).move_to_element(jiahao).perform()
            #     # jiahao.click()

            # try:
            #     print("加号点击了")
            # except Exception as e:
            #     errcount = errcount + 1
            #     print('异常次数超过三次:\t', errcount)
            #     # if errcount > 3:
            #     #     print('异常次数超过三次:\t', errcount)
            #     #     errcount = 0
            #     #     return True
            #
            #     print ('str(Exception):\t', str(Exception))
            #     print ('str(e):\t\t', str(e))
            #     print ('repr(e):\t', repr(e))
            #     # print ('e.message:\t', e.message)
            #     # button.click()
            #     # zfbut1 = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     # ActionChains(driver).move_to_element(zfbut1).perform()
            #     # if 'element not visible' in str(e) and errcount >5:
            #     #     errcount = 0
            #     #     print('元素找不到js操作一次:\t')
            #     #     js = 'document.getElementsByClassName("jiaohao")[0].click()'
            #     #     driver.execute_script(js)
            #     #     zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     #     ActionChains(driver).move_to_element(zfbut).perform()
            #     #     if is_element_visible(driver, zfbut):
            #     #         zfbut.click()
            #     #     else:
            #     #         button.click()
            #     #         zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     #         ActionChains(driver).move_to_element(zfbut).perform()
            #     #         zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     #         zfbut.click()
            #     #     zhuanfa_count = zhuanfa_count + 1
            #     #     return True
            #     # driver.execute_script("window.scrollTo(0,document.body.scrollHeight+document.body.clentHeight+20)")
            #     # continue
            # # button.click()
            # # time.sleep(10)
            # # jiahao.click()
            # print("加号点击了")
        # time.sleep(0.3)
        # dozf(driver,zfid,button)
    else:
        button.click()
        print('button点击后')
        time.sleep(3)
        zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//div[@class = "jiaohao"]')
        print("zfbut.click() is_element_visible(driver,zfbut)", is_element_visible(driver, zfbut))
        zfbut.click()
        dozf(driver, zfid, button)


def is_element_visible(driver, element):
    driver = driver
    try:
        the_element = EC.visibility_of_element_located(element)
        assert the_element(driver)
        flag = True
    except:
        flag = False
    return flag


def ifcomment(driver, nich):
    button1s = driver.find_elements_by_class_name("actor")
    for button in button1s:
        fav_class = button.get_attribute("href")
        if nich in fav_class:
            return False
    return True


# #评论
# buttons = driver.find_elements_by_class_name("commentTubiao")
# for button in buttons:
#     # print(button)
#     fav_class = button.get_attribute("class")
#     # print(fav_class)
#     if "notisGroup" not in fav_class:
#         print("单击评论")
#         button.click()  # 评论
#         time.sleep(1)
#         if ifcomment(driver,"hjy191"):
#             print("评论")
#         driver.find_element_by_css_selector("div.close").click()
#     time.sleep(1)

'''
print (len(buttons))
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(1)
buttons = driver.find_elements_by_class_name("v2_new_fav")
print (len(buttons))
'''

import threading


def fun():
    th = threading.Thread(target=dopx, args=())
    th.setDaemon(True)  # 守护线程
    th.start()


def dopx():
    login()
    while True:
        doit()
        try:
            driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        except ValueError:
            print('str(Exception):\t')
        finally:
            time.sleep(5)


root = Tk()
label1 = Label(root, text='0')
label2 = Label(root, text='0')
label3 = Label(root, text='0')


def threadGetCount():
    global label1
    while (True):
        label1['text'] = '累计点赞数:' + str(getPrice())
        label2['text'] = '累计转发数:' + str(getZhuanfa())
        label3['text'] = '累计留言数:' + str(getLiuyan())
        time.sleep(1)


def getPrice():
    global zan_count
    return zan_count


def getZhuanfa():
    global zhuanfa_count
    return zhuanfa_count


def getLiuyan():
    global liuyan_count
    return liuyan_count


# driver.quit()
if __name__ == '__main__':
    import datetime

    # global root
    # root.maxsize(600, 400)
    root.minsize(300, 240)
    end_date = datetime.datetime.strptime("2099-5-20", "%Y-%m-%d")
    datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
    begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d %H:%M:%S")
    print(end_date)
    print(datetimenowTime)
    print(begin_date)
    if begin_date < end_date:
        print('还能用')
        root.title(u"500px自动化点赞转发留言工具")
        label = Label(root, fg='green')
        label['text'] = u'正式版'
        label.pack()
        Button(root, text='启动', command=fun).pack()
        label1.pack()
        label2.pack()
        label3.pack()

        frame = Frame(root)
        frame.pack()
        lab1 = Label(frame, text="赞数限额:")
        lab1.grid(row=0, column=0, sticky=W)
        ent1 = Entry(frame)
        ent1.grid(row=0, column=1, sticky=W)
        ent1.insert(10, zan_max)
        lab2 = Label(frame, text="转发数限额:")
        lab2.grid(row=1, column=0)
        ent2 = Entry(frame)
        ent2.insert(10, zhuanfa_max)
        ent2.grid(row=1, column=1, sticky=W)
        lab3 = Label(frame, text="留言数限额:")
        lab3.grid(row=2, column=0)
        ent3 = Entry(frame)
        ent3.insert(10, liuyan_max)
        ent3.grid(row=2, column=1, sticky=W)
        lab4 = Label(frame, text="中文留言内容:")
        lab4.grid(row=3, column=0)
        ent4 = Entry(frame)
        ent4.insert(10, cn_liuyan)
        ent4.grid(row=3, column=1, sticky=W)
        lab5 = Label(frame, text="英文留言内容:")
        lab5.grid(row=4, column=0)
        ent5 = Entry(frame)
        ent5.insert(10, en_liuyan)
        ent5.grid(row=4, column=1, sticky=W)
        lab6 = Label(frame, text="登录手机号:")
        lab6.grid(row=5, column=0)
        ent6 = Entry(frame)
        ent6.insert(10, login_no)
        ent6.grid(row=5, column=1, sticky=W)
        lab7 = Label(frame, text="登录密码:")
        lab7.grid(row=6, column=0)
        ent7 = Entry(frame, show='*')
        ent7.insert(10, login_pw)
        ent7.grid(row=6, column=1, sticky=W)


        def Submit():
            global liuyan_max, zan_max, zhuanfa_max, cn_liuyan, en_liuyan, login_no, login_pw
            zan_max = ent1.get()
            zhuanfa_max = ent2.get()
            liuyan_max = ent3.get()
            cn_liuyan = ent4.get()
            en_liuyan = ent5.get()
            login_no = ent6.get()
            login_pw = ent7.get()


        button = Button(frame, text="保存", command=Submit)
        button.grid(row=7, column=1, sticky=E)

        center(root)
        t = threading.Thread(target=threadGetCount, args=(), name='thread-refresh')
        t.setDaemon(True)
        t.start()
        root.mainloop()
        # dopx()
    else:
        print('不能用')
        from tkinter import *

        root.title("提醒")
        label = Label(root)
        label['text'] = u'试用期已过，请联系 guocdfeifei@163.com 获取正式版'
        label.pack()
        center(root)
        root.mainloop()

